// import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:lib_database/objectbox.dart';
import 'package:lib_database/src/bean.dart';

// import 'package:lib_database/sp.dart';
// import 'package:lib_util/log/log.dart';
// import 'package:lib_util/utils/utils.dart';
enum LoadPageState { none, loading, error, empty }

class DAppCacheProvider extends ChangeNotifier {
  late List<DAppBean> cacheDAppList = [];

  // DAppIndexBean? dAppIndex;
  // LoadPageState dAppIndexState = LoadPageState.none;
  //String uid
  DAppCacheProvider() {
  }
  initData(String uid){
    refreshCacheDAppList(uid);
  }

  // loadDAppIndex(String lan, {bool showLoading = false}) async {
  //   dAppIndexState = LoadPageState.loading;
  //
  //   (showLoading
  //       ? EasyLoading.generateLoadingFuture(
  //       HttpRepository().requestDAppIndex(lan))
  //       : HttpRepository().requestDAppIndex(lan))
  //       .then((value) {
  //     dAppIndexState = LoadPageState.none;
  //     dAppIndex = value;
  //     SP().setDAppIndex(json.encode(dAppIndex));
  //     notifyListeners();
  //   }).onError((error, stackTrace) {
  //     dAppIndexState = LoadPageState.error;
  //     notifyListeners();
  //   });
  // }

  refreshCacheDAppList(String uid) {
    cacheDAppList = ObjectBox().cacheDAppModel.getAllCacheDApp(uid);
  }

  isCacheDAppExisted(DAppBean dApp) {
    return ObjectBox().cacheDAppModel.isCache(dApp);
  }

  getCacheDAppLength(String uid) {
    return ObjectBox().cacheDAppModel.getAllCacheLength(uid);
  }

  addOrRemoveCacheDApp(DAppBean dApp) {
    if (ObjectBox().cacheDAppModel.isCache(dApp)) {
      removeCache(dApp);
    } else {
      addCache(dApp);
    }
  }

  getCacheOneByUrl(String url, String uid) {
    return ObjectBox().cacheDAppModel.getCacheOneByUrl(url: url, uid: uid);
  }

  addCache(DAppBean dApp) {
    if (cacheDAppList.length >= 6) {
      DAppBean data = cacheDAppList[0];
      ObjectBox().cacheDAppModel.removeCacheDApp(data);
    }
    if (ObjectBox().cacheDAppModel.addCacheDApp(dApp)) {
      refreshCacheDAppList(dApp.uid!);
      notifyListeners();
    }
  }

  removeCache(DAppBean dApp) {
    if (ObjectBox().cacheDAppModel.removeCacheDApp(dApp)) {
      refreshCacheDAppList(dApp.uid!);
      notifyListeners();
    }
  }
}
